from pyglet.graphics import Group
from pyglet.sprite import Sprite

def TileableGroup(OrderedGroup):
    def __init__(self, *args, **kwargs):
        super(TileableGroup, self).__init__(*args, **kwargs)

    def set_state(self):
        
        glEnable(self.texture.target)
        glBindTexture(self.texture.target, self.texture.id)
        glPushAttrib(GL_ENABLE_BIT)
        glEnable(self.target)
        glBindTexture(self.target, self.id)
        glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
        glInterleavedArrays(GL_T4F_V4F, 0, array)


    def unset_state(self):
        glDisable(self.texture.target)

    def set_state_recursive(self):
        pass

class TileableSprite(Sprite):
    _tile_width = 0
    _tile_height = 0
    
    def _get_tile_width(self):
        return self._tile_width

    def _get_tile_height(self):
        return self._tile_height

    def _set_tile_width(self, width):
        self._tile_width = width
        self._update_position()

    def _set_tile_height(self, height):
        self._tile_height = height
        self._update_position()

    tile_width = property(_get_tile_width, _set_tile_width)
    tile_height = property(_get_tile_height, _set_tile_height)

    def __init__(self, *args, **kwargs):
        self._tile_width = kwargs.get('tile_width', 0)
        self._tile_height = kwargs.get('tile_height', 0)
        if self._tile_width or self._tile_height:
            del kwargs['tile_width']
            del kwargs['tile_height']
        super(TileableSprite, self).__init__(*args, **kwargs)
        if self._tile_width == 0 or self._tile_height == 0:
            self._tile_width, self._tile_height = self.width, self.height
        self._update_position()

    def _update_position(self):
        img = self._texture
        if not self._visible:
            self._vertex_list.vertices[:] = [0, 0, 0, 0, 0, 0, 0, 0]
        else:
            x, y = int(self._x), int(self._y)
            w, h = self.tile_width, self.tile_height
            u1 = self._texture.anchor_x / float(self._texture.width)
            v1 = self._texture.anchor_y / float(self._texture.height)
            u2 = u1 + w / float(self._texture.width)
            v2 = v1 + h / float(self._texture.height)
            t = self._texture.tex_coords
            self._vertex_list.vertices[:] = [ 
                x, y, x + w, y, x + w, y + h, x, y + h]
            self._vertex_list.tex_coords[:] = [u1, v1, t[2], u2, v1, t[5], u2, v2, t[8], u1, v2, t[11]]

    def __str__(self):
        return "Tile at (%d, %d)" % (self.x, self.y)
